import 'dart:convert';
import 'dart:typed_data';

import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.dart';

class HttpCryptUtil {
  ///签名
  static String xSignatureKey = 'SUJpkAqrNsaorId5';
  static String xSignatureIV = 'HYtZKEjFQ1EabCcx';

  ///请求密钥
  static Future requestCrypt() async {
    LogUtil.v('获取请求密钥 start');
    await Dio()
        .get(HttpUtil.getServerPath() + '/api/v1/request_crypt')
        .then((value) {
      LogUtil.v('获取请求密钥 end:${value.data}');
      //处理请求密钥
      // xSignatureKey = offsetKey(value.data['key'] ?? '', 0);
      // xSignatureIV = offsetKey(value.data['iv'] ?? '', 0);

      LogUtil.v('获取请求密钥 偏移后:$xSignatureKey-$xSignatureIV');
    });
    return true;
  }

  ///构造签名串
  static String createSignString({
    required String url,
    required String method,
    Map<String, dynamic>? queryParameters,
    dynamic data,
  }) {
    String nowDateMs =
        (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
    String bodyString = '';
    if (method == HttpUtil.MethodGet || method == HttpUtil.MethodDelete) {
      if (queryParameters != null) {
        bodyString = queryParameters.entries.map((entry) {
          return '${entry.key}=${entry.value}';
        }).join('&');
      }
    } else if (method == HttpUtil.MethodPost || method == HttpUtil.MethodPut) {
      if (data != null) {
        bodyString = json.encode(data);
      }
    }

    String result = '';
    String cryptBodyString = _generateMD5(bodyString);
    String urlResult = url.replaceAll(HttpUtil.getServerPath(), '');

    String initString = method +
        '\n' +
        urlResult +
        '\n' +
        nowDateMs +
        '\n' +
        cryptBodyString +
        '\n';
    LogUtil.v(
        'createSignString -method:$method  -url:$urlResult -nowDateMs:$nowDateMs -bodyString:$bodyString -cryptBodyString:$cryptBodyString   - $initString');

    result = _cryptSignString(initString);
    return result;
  }

  ///md5加密
  static String _generateMD5(String data) {
    Uint8List content = new Utf8Encoder().convert(data);
    Digest digest = md5.convert(content);
    return digest.toString();
  }

  static String offsetKey(String key, int offset) {
    String keyString = key;
    int keyOffset = offset;
    keyString =
        keyString.substring(keyString.length - keyOffset, keyString.length) +
            keyString.substring(0, keyString.length - keyOffset);
    return keyString;
  }

  ///加密签名串
  static String _cryptSignString(String plainText) {
    LogUtil.v('加密前:${plainText}');

    final key = Key.fromUtf8(xSignatureKey);

    final iv = IV.fromUtf8(xSignatureIV);

    final encrypter = Encrypter(AES(key, mode: AESMode.cbc, padding: 'PKCS7'));

    final encrypted = encrypter.encrypt(plainText, iv: iv);

    final decrypted = encrypter.decrypt(encrypted, iv: iv);

    LogUtil.v('加密后:${encrypted.base64}');
    LogUtil.v('解密后:${decrypted}');

    return encrypted.base64;
  }
}
